#!/usr/bin/env python
import os
import dbus
bus = dbus.SystemBus()
sbus = dbus.SessionBus()

def test_dbus(service):
    """
    Tests whether an a DBus service is running on the system bus. It has
    almost no use outside of net_connected itself.
    
    It takes the service name as a string, for example 'org.freedesktop.
    NetworkManager'.
    """ 
    obj = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
    iface = dbus.Interface(obj, 'org.freedesktop.DBus')
    
    sobj = sbus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
    siface = dbus.Interface(sobj, 'org.freedesktop.DBus')
    
    if service in iface.ListNames():
        return True
    elif service in siface.ListNames():
        return True
    else:
        return False

def net_connected():
    """
    Simple function to test whether the network is up and ready to go. By
    default, it uses NetworkManager over DBus to tell whether that daemon
    is connected or not. Otherwise, it uses the UNIX ping command to test
    whether it can connect with Google. The NM code is the preferred way,
    but it is not supported on all systems.
    """
    if test_dbus('org.freedesktop.NetworkManager') == True:
        networkstatus = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
        state = int(networkstatus.state())
    
        if state == 3:
            return True
        else:
            return False
    
    else:
        state = os.system('ping -c 1 google.com')
        
        if state == 0:
            return True
        else:
            return False
